package br.unesp.demac.bcc.soo.sistemaclarus.view;

import br.unesp.demac.bcc.soo.sistemaclarus.bean.Autor;
import br.unesp.demac.bcc.soo.sistemaclarus.bean.Editora;
import br.unesp.demac.bcc.soo.sistemaclarus.bean.Localizacao;
import br.unesp.demac.bcc.soo.sistemaclarus.bean.Obra;
import br.unesp.demac.bcc.soo.sistemaclarus.dao.ObraDAOImp;
import br.unesp.demac.bcc.soo.sistemaclarus.dao.LocalizacaoDAOImp;
import br.unesp.demac.bcc.soo.sistemaclarus.util.FrameUtil;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.text.MaskFormatter;
import javax.swing.JFormattedTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author Evaldo
 */
public class JFrameCadObras extends javax.swing.JFrame {

    /** Creates new form JFrameCadObras */
    public JFrameCadObras() {
        initComponents();
        
        JTable tblObras = new JTable();
        
        DefaultTableModel model = (DefaultTableModel)tblObras.getModel();
        model.setColumnCount(0);
        model.setRowCount(0);
        model.addColumn("Nome");
        model.addColumn("Ano de Publicação");
        model.addColumn("Editar");
        model.addColumn("Excluir");
        
        model.addRow(new Object[] {"Sistemas Operacionais", "2005", "", ""});
        model.addRow(new Object[] {"Aprendendo Java", "2008", "", ""});        
       
        DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer();
        tblObras.getColumnModel().getColumn(2).setCellRenderer(cellRenderer);
                
        TableColumn tc = tblObras.getColumnModel().getColumn(2);
        tc.setCellEditor(new DefaultCellEditor(new JComboBox()));
        /*renderer.setIcon(icEditar);
        TableColumnModel tableModel = tblObras.getColumnModel();
        TableColumn tc = tableModel.getColumn(2);
        tc.setCellRenderer(renderer);*/
        
        FrameUtil.centralizar(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblCadastrarObra = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        lblNomeObra = new javax.swing.JLabel();
        lblAnoPublicacao = new javax.swing.JLabel();
        lblEditora = new javax.swing.JLabel();
        lblLocalizacao = new javax.swing.JLabel();
        MaskFormatter maskAno = null;

        try{
            maskAno = new MaskFormatter("####");
            maskAno.setPlaceholderCharacter('_');

        }catch(ParseException ex){
            ex.printStackTrace();
        }
        txtAnoPublicacao = new JFormattedTextField(maskAno);
        txtNomeObra = new javax.swing.JTextField();
        txtNomeObra.setColumns(5);
        txtEditora = new javax.swing.JTextField();
        cbxLocalizacao = new javax.swing.JComboBox();
        LocalizacaoDAOImp locDao = new LocalizacaoDAOImp();
        List<Localizacao> lstLocalizacao = new ArrayList<Localizacao>();
        lstLocalizacao = locDao.buscaTodasLocalizacoes();

        cbxLocalizacao.addItem("---Selecione---");
        for (Localizacao loc : lstLocalizacao){
            cbxLocalizacao.addItem(loc);
        }
        lblAutores = new javax.swing.JLabel();
        txtAutores = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstAutores = new javax.swing.JList();
        btnAdicAutores = new javax.swing.JButton();
        btnRemovAutores = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        btnLimpar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastrar Obras");
        setResizable(false);

        lblCadastrarObra.setFont(new java.awt.Font("Calibri", 1, 18));
        lblCadastrarObra.setText("Cadastrar Obras");

        lblNomeObra.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblNomeObra.setText("Nome da Obra:");

        lblAnoPublicacao.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblAnoPublicacao.setText("Ano de Publicação:");

        lblEditora.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblEditora.setText("Editora:");

        lblLocalizacao.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblLocalizacao.setText("Localização:");

        lblAutores.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblAutores.setText("Autores:");

        jScrollPane1.setViewportView(lstAutores);

        btnAdicAutores.setText("+");
        btnAdicAutores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAdicAutoresActionPerformed(evt);
            }
        });

        btnRemovAutores.setText("-");
        btnRemovAutores.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemovAutoresActionPerformed(evt);
            }
        });

        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnLimpar.setText("Limpar");
        btnLimpar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimparActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 524, Short.MAX_VALUE)
                    .addComponent(lblCadastrarObra)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(lblAnoPublicacao)
                                    .addComponent(lblNomeObra)
                                    .addComponent(lblEditora)
                                    .addComponent(lblAutores)
                                    .addComponent(lblLocalizacao))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(cbxLocalizacao, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtEditora)
                                    .addComponent(txtNomeObra, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(txtAutores)
                                    .addComponent(txtAnoPublicacao, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(btnRemovAutores, 0, 0, Short.MAX_VALUE)
                                    .addComponent(btnAdicAutores, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnLimpar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(32, 32, 32)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblCadastrarObra)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNomeObra)
                    .addComponent(txtNomeObra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblAnoPublicacao)
                    .addComponent(txtAnoPublicacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblEditora)
                    .addComponent(txtEditora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbxLocalizacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblLocalizacao))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblAutores)
                    .addComponent(txtAutores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAdicAutores))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(btnRemovAutores)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSalvar)
                    .addComponent(btnLimpar))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAdicAutoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAdicAutoresActionPerformed
        
        if (! txtAutores.getText().trim().equals("")){
            ListModel model = lstAutores.getModel();
            
            DefaultListModel defaultModel = new DefaultListModel();
            
            if (model.getSize() > 0){
                for (int i = 0; i < model.getSize(); i++){
                    defaultModel.add(i, model.getElementAt(i));
                }
                defaultModel.add(model.getSize(), txtAutores.getText().trim());
            }
            else{
                defaultModel.add(0, txtAutores.getText().trim());
            }
            
            txtAutores.setText(null);
            lstAutores = new JList(defaultModel);
            jScrollPane1.setViewportView(lstAutores);
        }
        else{
            JOptionPane.showMessageDialog(this, "Preencha o campo autor.", "alerta", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnAdicAutoresActionPerformed

    private void btnRemovAutoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemovAutoresActionPerformed
        if (lstAutores.getSelectedValue() != null){
            ListModel model = lstAutores.getModel();
        
            DefaultListModel dfm = new DefaultListModel();
            for (int i = 0; i < model.getSize(); i++){
                dfm.add(i, model.getElementAt(i));
            }
            dfm.removeElement(lstAutores.getSelectedValue());

            lstAutores = new JList(dfm);
            jScrollPane1.setViewportView(lstAutores);
        }
        else{
            JOptionPane.showMessageDialog(this, "Selecione ao menos um autor", "Alerta", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btnRemovAutoresActionPerformed

    private void btnLimparActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimparActionPerformed
        limparControles();
    }//GEN-LAST:event_btnLimparActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        if (validarItensTela()){
            boolean statusInsercao = false;
            Obra obra = new Obra();
            
            obra.setNomeObra(txtNomeObra.getText().trim());
            obra.setAnoPublicacao(Integer.parseInt(txtAnoPublicacao.getText().trim()));
            
            //seta propriedades da editora
            Editora edit = new Editora();
            edit.setNomeEditora(txtEditora.getText().trim());
            obra.setEditora(edit);
            
            //seta propriedades da localização de acordo com a escolha no comboBox
            Localizacao local = (Localizacao) cbxLocalizacao.getSelectedItem();
            obra.setLocalizacao(local);
            
            //varre o JList para atribuir os autores da obra
            List<Autor> lstAutoresObra = new ArrayList<Autor>();
            ListModel model = lstAutores.getModel();
            
            for(int i = 0; i < model.getSize(); i++){
                Autor aut = new Autor();
                aut.setNomeAutor((String)model.getElementAt(i));
                lstAutoresObra.add(aut);
            }
            obra.setAutor(lstAutoresObra);      
            
            Date data = new Date(new java.util.Date().getTime());
            SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy");
            String dataFormatada = formatador.format(data);
            try{
                obra.setDataInclusao(formatador.parse(dataFormatada));
                
                ObraDAOImp obDao = new ObraDAOImp();
                statusInsercao = obDao.salvarObra(obra);
            }
            catch(ParseException ex){
                System.out.println("Erro na conversão." + ex.getMessage());
            }
            catch(SQLException ex){
                System.out.println("Erro na inserção." + ex.getMessage());
            }
            
            if (statusInsercao){
                limparControles();
                JOptionPane.showMessageDialog(this, "Obra inserida com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);                
            }
            else
                JOptionPane.showMessageDialog(this, "Problemas ao inserir a obra.", "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnSalvarActionPerformed

    /**
     * Verifica se todos itens obrigatórios da tela foram preenchidos
     * @return Status da validaçao
     */
    private boolean validarItensTela(){
        ListModel model = lstAutores.getModel();
        
        if (txtNomeObra.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Preencha o campo nome da obra.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else if (txtAnoPublicacao.getText().trim().equals("____")){
            JOptionPane.showMessageDialog(this, "Preencha o campo ano de publicação.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else if (txtEditora.getText().trim().equals("")){
            JOptionPane.showMessageDialog(this, "Preencha o campo editora.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else if (cbxLocalizacao.getSelectedIndex() == 0){
            JOptionPane.showMessageDialog(this, "Selecione uma localização.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        else if (model.getSize() == 0){
            JOptionPane.showMessageDialog(this, "Informe pelo menos um autor.", "Alerta", JOptionPane.WARNING_MESSAGE);
            return false;
        }
        
        return true;
    }
    
    /**
     * Limpa todos controles da tela
     */
    private void limparControles(){
        txtNomeObra.setText(null);
        txtAnoPublicacao.setText(null);
        txtEditora.setText(null);
        cbxLocalizacao.setSelectedIndex(0);
        txtAutores.setText(null);
        
        DefaultListModel defaultModel = new DefaultListModel();
        lstAutores = new JList(defaultModel);
        jScrollPane1.setViewportView(lstAutores);
    }
    
    private void clickedMouse(){
        txtNomeObra.setText("Click do Mouse");
    }
    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JFrameCadObras().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdicAutores;
    private javax.swing.JButton btnLimpar;
    private javax.swing.JButton btnRemovAutores;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox cbxLocalizacao;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblAnoPublicacao;
    private javax.swing.JLabel lblAutores;
    private javax.swing.JLabel lblCadastrarObra;
    private javax.swing.JLabel lblEditora;
    private javax.swing.JLabel lblLocalizacao;
    private javax.swing.JLabel lblNomeObra;
    private javax.swing.JList lstAutores;
    private javax.swing.JFormattedTextField txtAnoPublicacao;
    private javax.swing.JTextField txtAutores;
    private javax.swing.JTextField txtEditora;
    private javax.swing.JTextField txtNomeObra;
    // End of variables declaration//GEN-END:variables

}
